<template>
  <div class="contract-list-container">
    <!-- Tabs 标签页 -->
    <el-tabs v-model="activeTab" @tab-change="handleTabChange">
      <el-tab-pane label="合同总表" name="all"></el-tab-pane>
      <el-tab-pane label="进行中合同" name="notEnd"></el-tab-pane>
      <el-tab-pane label="待续租实体合同" name="nearly"></el-tab-pane>
      <el-tab-pane label="完结合同" name="finished"></el-tab-pane>
      <el-tab-pane label="待废弃合同" name="toBeDiscarded"></el-tab-pane>
      <el-tab-pane label="废弃合同" name="discarded"></el-tab-pane>
    </el-tabs>
    <el-card class="filter-card">
      <!-- 搜索表单 -->
      <el-form :model="queryParams" ref="queryForm" label-width="120px" :inline="true">
        <!-- 载体 -->
        <el-form-item label="载体" prop="carrierName">
          <el-select
            v-model="queryParams.carrierName"
            placeholder="请选择载体"
            clearable
            filterable
            style="width: 150px"
            :loading="dropdownLoading"
            @focus="handleSelectFocus('zt')"
          >
            <el-option
              v-for="item in ztOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="企业名称" prop="companyName">
          <el-input
            v-model="queryParams.companyName"
            placeholder="请输入企业名称"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="合同编号" prop="contractNumber">
          <el-input
            v-model="queryParams.contractNumber"
            placeholder="请输入合同编号"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <!-- 合同类型 -->
        <el-form-item label="合同类型" prop="type">
          <el-select
            v-model="queryParams.type"
            placeholder="请选择合同类型"
            clearable
            filterable
            style="width: 150px"
          >
            <el-option
              v-for="item in contractTypeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="handleQuery">查询</el-button>
          <el-button @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card class="list-card" style="margin-top: 18px">
      <!-- 表格 -->
      <el-table
        :data="tableData"
        border
        style="width: 100%"
        v-loading="loading"
        element-loading-text="正在加载..."
        row-key="id"
        max-height="500px"
        :expand-row-keys="expandedRowKeys"
        @expand-change="handleExpandChange"
      >
        <el-table-column type="expand">
          <template #default="props">
            <div class="payment-plan-container">
              <el-table
                :data="props.row.paymentPlanList || []"
                border
                style="width: 90%"
                v-loading="props.row.loading"
              >
                <el-table-column label="周期" min-width="200" align="left">
                  <template #default="{ row }">
                    {{ row.cycle }}
                  </template>
                </el-table-column>
                <el-table-column label="单价" width="120" align="left">
                  <template #default="{ row }"> {{ row.unitPrice }} 元 </template>
                </el-table-column>
                <el-table-column label="月价" width="120" align="left">
                  <template #default="{ row }"> {{ row.monthPrice }} 元 </template>
                </el-table-column>
                <el-table-column label="开始时间" width="150" align="left">
                  <template #default="{ row }">
                    {{ row.startTime }}
                  </template>
                </el-table-column>
                <el-table-column label="金额" width="120" align="left">
                  <template #default="{ row }"> {{ row.amount }} 元 </template>
                </el-table-column>
                <el-table-column label="状态" width="120" align="left">
                  <template #default="{ row }">
                    <el-tag :type="row.status === 3 ? 'success' : 'info'" size="small">
                      {{ row.statusDesc || "待处理" }}
                    </el-tag>
                  </template>
                </el-table-column>
                <el-table-column label="类型" width="120" align="left" fiexd="right">
                  <template #default="{ row }">
                    {{ row.type }}
                  </template>
                </el-table-column>
                <el-table-column label="备注" min-width="200" align="left" fixed="right">
                  <template #default="{ row }">
                    {{ row.remake }}
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </template>
        </el-table-column>

        <el-table-column label="合同编号" width="320" align="left">
          <template #default="{ row }">
            {{ row.contractNumber }}
          </template>
        </el-table-column>
        <el-table-column label="载体名称" width="180" align="left">
          <template #default="{ row }">
            {{ row.carrierName }}
          </template>
        </el-table-column>
        <el-table-column label="企业名称" width="300" align="left">
          <template #default="{ row }">
            {{ row.lesseeName }}
          </template>
        </el-table-column>
        <el-table-column label="合同类型" width="120" align="left">
          <template #default="{ row }">
            {{ row.type }}
          </template>
        </el-table-column>
        <el-table-column label="租赁期限" width="450" align="left">
          <template #default="{ row }">
            {{ row.leaseTerm }}
          </template>
        </el-table-column>
        <el-table-column label="租金单价" width="180" align="left">
          <template #default="{ row }">
            {{ formatUnitRentPrice(row.unitRentPrice) }} 元/平方米/月
          </template>
        </el-table-column>
        <el-table-column label="面积" width="150" align="left">
          <template #default="{ row }"> {{ row.area }} 平方米 </template>
        </el-table-column>
        <el-table-column label="物业类型" width="120" align="left">
          <template #default="{ row }">
            {{ row.propertyType }}
          </template>
        </el-table-column>
        <el-table-column label="金额" width="120" align="left">
          <template #default="{ row }"> {{ row.amount }} 元 </template>
        </el-table-column>
        <el-table-column label="付款方式" width="150" align="left">
          <template #default="{ row }">
            {{ row.paymentTerms }}
          </template>
        </el-table-column>
        <el-table-column label="租赁保证金" width="150" align="left">
          <template #default="{ row }"> {{ row.securityDeposit }} 元 </template>
        </el-table-column>
        <el-table-column label="状态" width="100" align="left">
          <template #default="{ row }">
            <el-tag
              :type="
                row.status === 'draft'
                  ? 'warning'
                  : row.status === 'generated'
                  ? 'success'
                  : 'info'
              "
              size="small"
            >
              {{
                row.status === "draft"
                  ? "草稿"
                  : row.status === "generated"
                  ? "已生成"
                  : "已归档"
              }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="250" fixed="right" align="left">
          <template #default="{ row }">
            <el-button type="primary" link @click="handleLinkToCompany(row)"
              >查看企业档案</el-button
            >
            <el-button type="primary" link @click="showContractDetail(row)"
              >查看合同详情</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @pagination="handlePagination"
      />
    </el-card>
    <!-- 分页 -->

    <PaymentModal
      v-model="showPaymentModal"
      :company-id="currentCompanyId"
      :plan-id="currentPlanId"
      @success="handlePaymentSuccess"
      @close="handlePaymentClose"
    />
    <!-- 合同详情抽屉 -->
    <el-drawer
      v-model="drawerVisible"
      title="合同详情"
      size="50%"
      :before-close="handleDrawerClose"
    >
      <div class="drawer-content">
        <!-- 合同信息卡片 -->
        <el-card class="info-card">
          <template #header>
            <div class="card-header">
              <span>合同信息</span>
            </div>
          </template>
          <el-descriptions :column="2" border align="left">
            <el-descriptions-item label="合同编号" align="left">{{
              contractDetail.contractNumber
            }}</el-descriptions-item>
            <el-descriptions-item label="载体名称" align="left">{{
              contractDetail.carrierName
            }}</el-descriptions-item>
            <el-descriptions-item label="企业名称" align="left">{{
              contractDetail.lesseeName
            }}</el-descriptions-item>
            <el-descriptions-item label="租赁期限" align="left">{{
              contractDetail.leaseTerm
            }}</el-descriptions-item>
            <el-descriptions-item label="租金单价" align="left"
              >{{
                formatUnitRentPrice(contractDetail.unitRentPrice)
              }}
              元/平方米/月</el-descriptions-item
            >
            <el-descriptions-item label="面积" align="left"
              >{{ contractDetail.area }} 平方米</el-descriptions-item
            >
            <el-descriptions-item label="物业类型" align="left">{{
              contractDetail.propertyType
            }}</el-descriptions-item>
            <el-descriptions-item label="金额" align="left"
              >{{ contractDetail.amount }} 元</el-descriptions-item
            >
            <el-descriptions-item label="付款方式" align="left">{{
              contractDetail.paymentTerms
            }}</el-descriptions-item>
            <el-descriptions-item label="租赁保证金" align="left"
              >{{ contractDetail.securityDeposit }} 元</el-descriptions-item
            >
            <el-descriptions-item label="合同状态" align="left">
              <el-tag
                :type="
                  contractDetail.status === 'draft'
                    ? 'warning'
                    : contractDetail.status === 'generated'
                    ? 'success'
                    : 'info'
                "
              >
                {{
                  contractDetail.status === "draft"
                    ? "草稿"
                    : contractDetail.status === "generated"
                    ? "已生成"
                    : "已归档"
                }}
              </el-tag>
            </el-descriptions-item>
          </el-descriptions>
        </el-card>

        <!-- 回款计划卡片 -->
        <el-card class="info-card">
          <template #header>
            <div class="card-header">
              <span>回款计划</span>
              <el-button
                type="primary"
                size="small"
                @click="handleAddPaymentHistory"
                v-if="companyInfo.status >= 3"
              >
                <i-ep-plus />新增缴费流水
              </el-button>
            </div>
          </template>

          <!-- 新增缴费流水表单 -->
          <el-form
            v-if="paymentHistoryDialogVisible"
            :model="paymentHistoryForm"
            :rules="paymentHistoryRules"
            ref="paymentHistoryFormRef"
            label-width="100px"
            class="payment-history-form"
          >
            <el-row :gutter="20">
              <el-col :span="10">
                <el-form-item label="总金额" prop="amount">
                  <el-input-number
                    v-model="paymentHistoryForm.amount"
                    :min="0"
                    :precision="2"
                    :step="100"
                    controls-position="right"
                    style="width: 100%"
                    placeholder="请输入总金额"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="14">
                <el-form-item label="合同编号">
                  <el-input
                    v-model="paymentHistoryForm.contractNumber"
                    disabled
                    style="width: 100%"
                  />
                </el-form-item>
              </el-col>
            </el-row>

            <div class="form-actions">
              <el-button @click="paymentHistoryDialogVisible = false">取消</el-button>
              <el-button type="primary" @click="submitPaymentHistoryForm">确定</el-button>
            </div>
          </el-form>

          <el-table :data="paymentPlans" border>
            <el-table-column prop="cycle" label="周期" width="300" align="left" />
            <el-table-column prop="unitPrice" label="单价" width="120" align="left">
              <template #default="{ row }">{{ row.unitPrice }} 元</template>
            </el-table-column>
            <el-table-column prop="monthPrice" label="月价" width="120" align="left">
              <template #default="{ row }">{{ row.monthPrice }} 元</template>
            </el-table-column>
            <el-table-column prop="startTime" label="开始时间" width="180" align="left" />
            <el-table-column prop="amount" label="金额" width="120" align="left">
              <template #default="{ row }">{{ row.amount }} 元</template>
            </el-table-column>
            <el-table-column prop="statusDesc" label="状态" width="120" align="left">
              <template #default="{ row }">
                <el-tag :type="row.status === 3 ? 'success' : 'info'">
                  {{ row.statusDesc || "待处理" }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="type" label="类型" width="120" align="left">
              <template #default="{ row }">{{ row.type }}</template>
            </el-table-column>
            <el-table-column prop="remake" label="备注" width="200" align="left">
              <template #default="{ row }">{{ row.remake }}</template>
            </el-table-column>
          </el-table>
        </el-card>

        <!-- 缴费流水卡片 -->
        <el-card class="info-card">
          <template #header>
            <div class="card-header">
              <span>缴费流水</span>
            </div>
          </template>
          <el-table :data="paymentHistoryData" border v-loading="historyLoading">
            <el-table-column type="index" label="序号" width="80" align="left" />
            <el-table-column
              prop="contractNumber"
              label="合同编号"
              width="250"
              align="left"
            />
            <el-table-column prop="amount" label="总金额" width="120" align="left" />
            <el-table-column
              prop="remainingAmount"
              label="剩余金额"
              width="120"
              align="left"
            />
            <el-table-column
              prop="paidAmount"
              label="已付金额"
              align="left"
              width="120"
            />
            <el-table-column
              prop="createTime"
              label="创建时间"
              align="left"
              width="180"
            />
            <el-table-column
              prop="updateTime"
              label="修改时间"
              align="left"
              width="180"
            />
            <!-- <el-table-column label="操作" width="150" align="left" fixed="right">
              <template #default="{ row }">
              
                <el-button type="danger" link @click="handleDeletePaymentHistory(row)">
                  <i-ep-delete />删除
                </el-button>
              </template> -->
            <!-- </el-table-column> -->
          </el-table>
          <!-- 缴费流水分页组件 -->
          <pagination
            v-show="historyTotal > 0"
            :total="historyTotal"
            :page="historyQueryParams.pageNum"
            :limit="historyQueryParams.pageSize"
            @pagination="handleHistoryPagination"
            class="pagination-container"
          />
        </el-card>

        <!-- 回款明细卡片 -->
        <el-card class="info-card">
          <template #header>
            <div class="card-header">
              <span>回款明细</span>
            </div>
          </template>
          <el-table :data="paymentLogData" border v-loading="logLoading">
            <el-table-column type="index" label="序号" width="100" />
            <el-table-column prop="planId" label="计划ID" width="180" />
            <el-table-column prop="historyId" label="流水ID" width="180" />
            <el-table-column prop="amount" label="缴费金额" width="180" />
            <el-table-column prop="createTime" label="创建时间" width="180" />
            <el-table-column prop="updateTime" label="修改时间" width="180" />
          </el-table>
          <!-- 回款明细分页组件 -->
          <pagination
            v-show="logTotal > 0"
            :total="logTotal"
            :page="logQueryParams.pageNum"
            :limit="logQueryParams.pageSize"
            @pagination="handleLogPagination"
            class="pagination-container"
          />
        </el-card>

        <!-- 关联企业卡片 -->
        <el-card class="info-card">
          <template #header>
            <div class="card-header">
              <span>关联企业</span>
            </div>
          </template>
          <el-descriptions :column="3" border align="left">
            <el-descriptions-item label="企业名称" align="left">{{
              companyInfo.companyName
            }}</el-descriptions-item>
            <el-descriptions-item label="载体" align="left">{{
              companyInfo.zt
            }}</el-descriptions-item>
            <el-descriptions-item label="注册资金" align="left">{{
              companyInfo.registeredCapital
            }}</el-descriptions-item>
            <el-descriptions-item label="预计税收(万)" align="left">{{
              companyInfo.estimatedTaxRevenue
            }}</el-descriptions-item>
            <el-descriptions-item label="入驻方式" align="left">{{
              companyInfo.entryMode
            }}</el-descriptions-item>
            <el-descriptions-item label="行业分类" align="left">{{
              companyInfo.industryCategory
            }}</el-descriptions-item>
            <el-descriptions-item label="招商员" align="left">{{
              companyInfo.merchants
            }}</el-descriptions-item>
            <el-descriptions-item label="注册类型" align="left">{{
              companyInfo.companyClass
            }}</el-descriptions-item>

            <el-descriptions-item label="房间号" align="left">{{
              companyInfo.roomNum
            }}</el-descriptions-item>
            <el-descriptions-item label="入驻状态" align="left">
              <el-tag type="primary">{{
                !companyInfo.status || companyInfo.status == 0
                  ? "未开始入驻流程"
                  : companyInfo.status == 1
                  ? "备案中"
                  : companyInfo.status == 2
                  ? "合同拟定中"
                  : companyInfo.status == 3
                  ? "办证中"
                  : companyInfo.status == 4 && companyInfo.processId
                  ? "入驻中流程"
                  : "入驻中"
              }}</el-tag>
            </el-descriptions-item>
          </el-descriptions>
        </el-card>
      </div>
    </el-drawer>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from "vue";
import { useRoute, useRouter } from "vue-router";
import { getCurrentInstance } from "vue";

const { proxy } = getCurrentInstance();
// 引入API
import {
  DraftContractAllList,
  getCompanyInfoByContractNumber,
  insertPaymentHistory,
  updatePaymentHistory,
  getPaymentHistoryList,
  payment_logList,
  deletePaymentHistory,
  getPaymentPlanList,
} from "@/api/company/info.js";

// 定义响应式数据
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  carrierName: "",
  companyName: "",
  contractNumber: "",
  status: "",
  isNearly: "", // 用于筛选待续租实体
  isNotEnd: "", // 用于筛选进行中合同
  type: null,
});

// 展开行相关状态
const expandLoading = ref({});
const expandedRowKeys = ref([]); // 当前展开的行key数组
const currentExpandedRow = ref(null); // 当前展开的行

const tableData = ref([]);
const total = ref(0);
const loading = ref(false);
const activeTab = ref("all"); // 默认选中合同总表

// 获取路由和路由器实例
const route = useRoute();
const router = useRouter();

import PaymentModal from "@/views/PaymentModal.vue";
import { getBaseCodeInfoList } from "@/api/AttractInvestment/baseCode/index.js";

// 缴费弹窗相关
const showPaymentModal = ref(false);
const currentCompanyId = ref("");
const currentPlanId = ref("");

// 合同详情抽屉相关
const drawerVisible = ref(false);
const contractDetail = ref({});
const paymentPlans = ref([]);
const companyInfo = ref({});

// 缴费流水表单相关
const paymentHistoryDialogVisible = ref(false);
const paymentHistoryForm = reactive({
  id: null,
  companyId: "",
  amount: 0,
  companyName: "",
  remainingAmount: 0,
  contractNumber: "",
  paidAmount: 0,
  status: 0,
});
const paymentHistoryFormRef = ref();

// 缴费流水表单验证规则
const paymentHistoryRules = {
  amount: [{ required: true, message: "请输入总金额", trigger: "blur" }],
};

// 缴费流水列表相关
const paymentHistoryData = ref([]);
const historyTotal = ref(0);
const historyLoading = ref(false);
const historyQueryParams = reactive({
  pageNum: 1,
  pageSize: 10,
});

// 回款明细列表相关
const paymentLogData = ref([]);
const logTotal = ref(0);
const logLoading = ref(false);
const logQueryParams = reactive({
  pageNum: 1,
  pageSize: 10,
});

const formatUnitRentPrice = (value) => {
  if (value === null || value === undefined || value === "") {
    return "0.00";
  }
  const num = Number(value);
  if (!Number.isFinite(num)) {
    return value;
  }
  return num.toFixed(2);
};

// 处理缴费操作
function handlePayment(row) {
  currentCompanyId.value = row.companyId;
  currentPlanId.value = row.id;
  showPaymentModal.value = true;
}

// 缴费成功回调
function handlePaymentSuccess() {
  // 重新刷新列表
  fetchDraftContractList();
  // 关闭弹窗组件
  showPaymentModal.value = false;
}

// 关闭弹窗回调
function handlePaymentClose() {
  // 关闭弹窗组件
  showPaymentModal.value = false;
}

// 关闭抽屉
function handleDrawerClose() {
  drawerVisible.value = false;
}
// 获取草稿合同列表
async function fetchDraftContractList() {
  try {
    loading.value = true;
    const res = await DraftContractAllList(queryParams);
    if (res.code == 200) {
      tableData.value = res.rows || [];
      total.value = res.total || 0;
    } else {
      proxy.$modal.msgError(res.msg || "获取数据失败");
    }
  } catch (error) {
    console.error("获取草稿合同列表失败:", error);
  } finally {
    setTimeout(() => {
      loading.value = false;
    }, 300);
  }
}

// 查询
function handleQuery() {
  queryParams.pageNum = 1;
  fetchDraftContractList();
}

// 重置查询条件
function resetQuery() {
  queryParams.carrierName = "";
  queryParams.companyName = "";
  queryParams.contractNumber = "";
  queryParams.status = "";
  queryParams.isNearly = "";
  queryParams.isNotEnd = "";
  queryParams.pageNum = 1;
  queryParams.type = null;
  queryParams.pageSize = 10;
  fetchDraftContractList();
}

// 分页处理
function handlePagination({ page, limit }) {
  queryParams.pageNum = page;
  queryParams.pageSize = limit;
  fetchDraftContractList();
}

// 查看企业档案
function handleLinkToCompany(row) {
  // 跳转到LookCompany页面，携带companyId参数
  router.push({
    path: "/lookCompany",
    query: {
      companyId: row.companyId,
    },
  });
}

// 显示合同详情
async function showContractDetail(row) {
  try {
    loading.value = true;
    console.log("showContractDetail row:", row.contractNumber);
    // 获取企业信息
    const companyRes = await getCompanyInfoByContractNumber({
      contractNumber: row.contractNumber,
    });
    if (companyRes.code !== 200) {
      proxy.$modal.msgError(companyRes.msg || "获取企业信息失败");
      return;
    }

    contractDetail.value = row || {};
    paymentPlans.value = row.paymentPlanList || [];
    companyInfo.value = companyRes.data || {};
    drawerVisible.value = true;

    // 加载缴费流水和回款明细
    fetchPaymentHistory();
    fetchPaymentLog();
  } catch (error) {
    console.error("获取详情失败:", error);
  } finally {
    loading.value = false;
  }
}

// 新增缴费流水
const handleAddPaymentHistory = () => {
  resetPaymentHistoryForm();
  paymentHistoryForm.companyId = companyInfo.value.companyId;
  paymentHistoryForm.companyName = companyInfo.value.companyName;
  paymentHistoryForm.contractNumber = contractDetail.value.contractNumber; // 直接使用当前合同编号
  paymentHistoryDialogVisible.value = true;
};

// 重置缴费流水表单
const resetPaymentHistoryForm = () => {
  paymentHistoryForm.id = null;
  paymentHistoryForm.companyId = companyInfo.value.companyId || "";
  paymentHistoryForm.amount = 0;
  paymentHistoryForm.companyName = "";
  paymentHistoryForm.remainingAmount = 0;
  paymentHistoryForm.contractNumber = "";
  paymentHistoryForm.paidAmount = 0;
  paymentHistoryForm.status = 0;
};

// 提交缴费流水表单
const submitPaymentHistoryForm = () => {
  paymentHistoryFormRef.value.validate(async (valid) => {
    if (!valid) return;

    try {
      paymentHistoryForm.remainingAmount = paymentHistoryForm.amount;
      // 根据是否有id判断是新增还是修改
      if (paymentHistoryForm.id) {
        await updatePaymentHistory(paymentHistoryForm);
      } else {
        await insertPaymentHistory(paymentHistoryForm);
      }

      proxy.$modal.msgSuccess(paymentHistoryForm.id ? "修改成功" : "新增成功");
      paymentHistoryDialogVisible.value = false;
      // 刷新数据
      fetchPaymentHistory();
      fetchPaymentLog();
      showContractDetail(contractDetail.value);
    } catch (error) {
      console.error("提交缴费流水表单失败:", error);
    }
  });
};

// 获取缴费流水
const fetchPaymentHistory = async () => {
  if (!companyInfo.value.companyId) return;

  historyLoading.value = true;
  try {
    const params = {
      companyId: companyInfo.value.companyId,
      pageNum: historyQueryParams.pageNum,
      pageSize: historyQueryParams.pageSize,
    };

    const res = await getPaymentHistoryList(params);
    if (res && res.code == 200) {
      let rows = [];
      if (Array.isArray(res.rows)) {
        rows = res.rows;
      } else if (
        res.rows &&
        typeof res.rows === "object" &&
        typeof res.rows.length === "number"
      ) {
        rows = Array.from(res.rows);
      }
      paymentHistoryData.value = rows;
      historyTotal.value = res.total || 0;
    } else {
      paymentHistoryData.value = [];
      historyTotal.value = 0;
    }
  } catch (error) {
    console.error("获取缴费流水失败:", error);
    paymentHistoryData.value = [];
    historyTotal.value = 0;
  } finally {
    historyLoading.value = false;
  }
};

// 修改缴费流水
const handleEditPaymentHistory = (row) => {
  resetPaymentHistoryForm();
  Object.assign(paymentHistoryForm, row, {
    companyId: companyInfo.value.companyId,
  });
  paymentHistoryDialogVisible.value = true;
};

// 删除缴费流水
const handleDeletePaymentHistory = async (row) => {
  try {
    await proxy.$modal.confirm("确定要删除该缴费流水吗？");
    await deletePaymentHistory(row.id);
    proxy.$modal.msgSuccess("删除成功");
    fetchPaymentHistory();
    fetchCompanyInfo();
  } catch (error) {
    if (error !== "cancel") {
      console.error("删除缴费流水失败:", error);
    }
  }
};

// 缴费流水分页处理
const handleHistoryPagination = ({ page, limit }) => {
  historyQueryParams.pageNum = page;
  historyQueryParams.pageSize = limit;
  fetchPaymentHistory();
};

// 获取回款明细
const fetchPaymentLog = async () => {
  if (!companyInfo.value.companyId) return;

  logLoading.value = true;
  try {
    const params = {
      companyId: companyInfo.value.companyId,
      pageNum: logQueryParams.pageNum,
      pageSize: logQueryParams.pageSize,
    };

    const res = await payment_logList(params);
    if (res && res.code == 200) {
      let rows = [];
      if (Array.isArray(res.rows)) {
        rows = res.rows;
      } else if (
        res.rows &&
        typeof res.rows === "object" &&
        typeof res.rows.length === "number"
      ) {
        rows = Array.from(res.rows);
      }
      paymentLogData.value = rows;
      logTotal.value = res.total || 0;
    } else {
      paymentLogData.value = [];
      logTotal.value = 0;
    }
  } catch (error) {
    console.error("获取回款明细失败:", error);
    paymentLogData.value = [];
    logTotal.value = 0;
  } finally {
    logLoading.value = false;
  }
};

// 回款明细分页处理
const handleLogPagination = ({ page, limit }) => {
  logQueryParams.pageNum = page;
  logQueryParams.pageSize = limit;
  fetchPaymentLog();
};

// Tabs切换处理
function handleTabChange(tabName) {
  // 根据标签页设置参数
  if (tabName === "nearly") {
    queryParams.isNearly = true;
    queryParams.isNotEnd = "";
    queryParams.type = "实体";
    queryParams.status = "";
  } else if (tabName === "notEnd") {
    queryParams.isNotEnd = 1;
    queryParams.isNearly = "";
    queryParams.status = "";
    queryParams.type = null;
  } else if (tabName === "discarded") {
    // 废弃合同，设置status为3（已废弃）
    queryParams.status = 3;
    queryParams.isNotEnd = "";
    queryParams.type = null;
    queryParams.isNearly = "";
  } else if (tabName === "finished") {
    // 完结合同，设置status为1（已完结）
    queryParams.status = 1;
    queryParams.isNotEnd = "";
    queryParams.isNearly = "";
    queryParams.type = null;
  } else if (tabName === "toBeDiscarded") {
    // 待废弃合同，设置status为2（待废弃）
    queryParams.status = 2;
    queryParams.isNotEnd = "";
    queryParams.type = null;
    queryParams.isNearly = "";
  } else {
    queryParams.isNearly = "";
    queryParams.isNotEnd = "";
    queryParams.type = null;
    queryParams.status = "";
  }

  // 重置页码并重新获取数据
  queryParams.pageNum = 1;
  fetchDraftContractList();
}

// 展开行处理
const handleExpandChange = async (row, expandedRows) => {
  if (expandedRows.includes(row)) {
    // 展开行时加载回款计划数据
    if (!row.paymentPlanList || row.paymentPlanList.length === 0) {
      await fetchPaymentPlanForRow(row);
    }

    // 设置当前展开的行
    currentExpandedRow.value = row;
    expandedRowKeys.value = [row.id]; // 只展开当前行
  } else {
    // 收起行时清空
    if (currentExpandedRow.value && currentExpandedRow.value.id === row.id) {
      currentExpandedRow.value = null;
      expandedRowKeys.value = [];
    }
  }
};

// 获取单行的回款计划数据
async function fetchPaymentPlanForRow(row) {
  try {
    // 设置加载状态
    row.loading = true;

    // 调用接口获取回款计划数据
    const params = {
      companyId: row.companyId,
      // 洪洞编号参数，根据实际情况调整参数名
      contractNumber: row.contractNumber,
    };

    const res = await getPaymentPlanList(params);
    if (res.code === 200) {
      // 更新该行的回款计划数据
      row.paymentPlanList = res.rows || [];
    } else {
      proxy.$modal.msgError(res.msg || "获取回款计划失败");
      row.paymentPlanList = [];
    }
  } catch (error) {
    console.error("获取回款计划失败:", error);
    row.paymentPlanList = [];
    proxy.$modal.msgError("获取回款计划失败");
  } finally {
    row.loading = false;
  }
}

// 页面加载时获取数据
onMounted(() => {
  fetchDraftContractList();
});

// 载体下拉
const dropdownLoading = ref(false);
const ztOptions = ref([]);
const contractTypeOptions = [
  { label: "实体", value: "实体" },
  { label: "虚拟", value: "虚拟" },
];
const handleSelectFocus = async (key) => {
  if (key !== "zt") return;
  if (ztOptions.value && ztOptions.value.length > 0) return; // 已加载过
  dropdownLoading.value = true;
  try {
    // 与 customerList.vue 一致：bigCategory=35 → projectList（载体/项目）
    const res = await getBaseCodeInfoList({ bigCategory: 35 });
    if (res && res.code === 200 && Array.isArray(res.rows)) {
      ztOptions.value = res.rows.map((item) => ({
        label: item.content,
        value: item.content,
      }));
    } else {
      ztOptions.value = [];
    }
  } catch (e) {
    console.error("获取载体下拉失败:", e);
    ztOptions.value = [];
  } finally {
    dropdownLoading.value = false;
  }
};
</script>

<style scoped>
.contract-list-container {
  padding: 20px;
}

.payment-plan-container {
  padding: 20px;
}

.drawer-content {
  padding: 20px;
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.info-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-weight: bold;
  font-size: 16px;
}

.el-descriptions {
  margin-top: 10px;
}

.payment-history-form {
  margin-bottom: 20px;
  padding: 20px;
  border-radius: 6px;
}

.form-actions {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  margin-top: 20px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}
</style>
